﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNet.Auth.Service;
using DotNet.Auth.Utility;
using DotNet.Web.Areas.AuthWeb.Controllers;

namespace DotNet.Web.Areas.Mobile.Controllers
{
    public class M_LoginController : AuthController
    {
        // GET: Mobile/M_Login
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult home()
        {
            return View();
        }
        [AllowAnonymous]
        public ActionResult M_login()
        {
            return View();
        }
        [HttpPost]
        [AllowAnonymous]
        public ActionResult M_Login(string account, string password)
        {
            account = account.Trim();
            var userService = AuthService.User;
            var result = userService.Login(account, password);
            if (result.Success) //登陆成功
            {
                var entity = userService.GetByAccount(account);
                var employee = new JCore.Service.EmployeeService().GetByUserId(entity.Id);
                if (employee == null)
                {
                    return Json(new { success = false, message = "请指定账号与员工的绑定关系" });
                }

                new JCore.Service.AccountLogService().Insert(employee, 0);

                FormsAuthentication.SetAuthCookie(account, false);

                var audit = AuthHelper.BuildAuditEntity(1, entity);
                AuthService.Audit.Create(audit);

                var suser = AuthHelper.BuildSessionUser(AuthService.User.GetByAccount(account));
                AuthHelper.SetSessionUser(suser);

                return Json(new { success = true, message = "登陆成功", url = "M_Login/home" });
            }
            return Json(result);
        }
        public ActionResult Logout()
        {
            //string URL = "/Mobile/M_Login";
            //URL = Url.Action("M_Login");
            var audit = AuthHelper.BuildAuditEntity(2, AuthHelper.GetSessionUser()?.User);
            AuthService.Audit.Create(audit);
            var suser = AuthHelper.GetSessionUser();
            if (suser != null && suser.User != null)
            {
                var employee = new JCore.Service.EmployeeService().GetByUserId(suser.Id);
                if (employee != null)
                {
                    new JCore.Service.AccountLogService().Insert(employee, 1);
                }
            }
            FormsAuthentication.SignOut();
            return RedirectToAction("M_Login");
            //return Redirect(URL);
        }
    }
}